#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sort.h"

// 辅助函数：验证数组是否已排序
int is_sorted(int *data, int size) {
    for (int i = 0; i < size - 1; i++) {
        if (data[i] > data[i + 1]) {
            return 0; // 数组未排序
        }
    }
    return 1; // 数组已排序
}

// 辅助函数：复制数组
void copy_array(int *src, int *dst, int size) {
    memcpy(dst, src, size * sizeof(int));
}

// 测试函数
void test_sort_function(int (*sort_func)(int *, int), int *data, int size, const char *func_name) {
    int *test_data = (int *)malloc(size * sizeof(int));
    if (test_data == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return;
    }

    copy_array(data, test_data, size);
    sort_func(test_data, size);

    if (is_sorted(test_data, size)) {
        printf("%s passed the test.\n", func_name);
    } else {
        printf("%s failed the test.\n", func_name);
    }

    free(test_data);
}

// 测试快速排序函数
void test_quick_sort(int *data, int size) {
    int *test_data = (int *)malloc(size * sizeof(int));
    if (test_data == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return;
    }

    copy_array(data, test_data, size);
    quick_sort(test_data, 0, size - 1);

    if (is_sorted(test_data, size)) {
        printf("quick_sort passed the test.\n");
    } else {
        printf("quick_sort failed the test.\n");
    }

    free(test_data);
}

int main() {
    int data[] = {5, 4, 3, 2, 1};
    int size = sizeof(data) / sizeof(data[0]);

    test_sort_function(select_sort, data, size, "select_sort");
    test_sort_function(insert_sort, data, size, "insert_sort");
    test_sort_function(bubble_sort, data, size, "bubble_sort");
    test_quick_sort(data, size);

    return 0;
}